package org.xxpay.pay.task;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.AlipayCash;
import org.xxpay.core.service.IXxPayAlipayCashService;
import org.xxpay.pay.service.CommonService;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Component
public class AlipayCashStatusScheduled extends ReissuceBase {

    private static final MyLog _log = MyLog.getLog(AlipayCashStatusScheduled.class);

    @Autowired
    private CommonService commonService;

    @Autowired
    private IXxPayAlipayCashService XxPayAlipayCashService;

    /** 支付宝红包- 状态 定时任务 **/
    @Scheduled(cron="0 0/1 * * * ?") //每分钟执行一次
    public void statusTask() {
        final String logPrefix = "【支付宝红包_状态查询】";

        // 支付补单开关(与补单开关公用一个)
        DBApplicationConfig dbConfig = commonService.sysConfigService.getDBApplicationConfig();
        if(!isExcuteReissueTask(dbConfig.getTaskReissuePaySwitch(), dbConfig.getTaskReissuePayIp())) {
            //_log.info("{}当前机器不执行支付宝红包状态处理任务", logPrefix);
            return;
        }

        //查询条件
        AlipayCash queryCondition = new AlipayCash();

        //查询1分钟以前创建的红包任务， 避免出现查询支付宝返回特殊状态
        queryCondition.setPsVal("createTimeLe", DateUtils.addMinutes(new Date(), 1));

        //查询支付包状态为 【已创建未打款， 已打款， 活动已开始】（非终结状态）
        queryCondition.setPsVal("alipayStatusIn", Arrays.asList(AlipayCash.ALIPAY_STATUS_INIT, AlipayCash.ALIPAY_STATUS_CREATED,
                                                        AlipayCash.ALIPAY_STATUS_PAID, AlipayCash.ALIPAY_STATUS_READY));

        int currentPageIndex = 1; //当前页码
        int pageSize = 100; //每次查询数量
        while(true){

            int offSet = ( currentPageIndex++ -1 ) * pageSize;  //计算分页偏移量
            List<AlipayCash> taskList = commonService.alipayCashService.select(offSet, pageSize, queryCondition);
            if(taskList == null || taskList.isEmpty()){ //本次查询无结果, 不再继续查询;
                break;
            }

            for(AlipayCash cashItem: taskList){
                try {
                    String alipayStatus = XxPayAlipayCashService.updateInfoFromAlipay(cashItem.getId());  //更新状态
                    _log.info("{}查询cashId={}, 支付宝返回最新状态为：{}", logPrefix, cashItem.getId(), alipayStatus);

                } catch (Exception e) {  //继续下一次迭代查询
                    _log.error("error cashId = {}", cashItem.getId(), e);
                }
            }
        }
    }

}
